#region --- License & Copyright Notice ---
/*
ConsoleFx CommandLine Processing Library

Copyright (c) 2006-2012 Jeevan James
All rights reserved.

The contents of this file are made available under the terms of the
Eclipse Public License v1.0 (the "License") which accompanies this
distribution, and is available at the following URL:
http://opensource.org/licenses/eclipse-1.0.txt

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.

By using this software in any fashion, you are agreeing to be bound by the
terms of the License.
*/
#endregion

using System.Collections.ObjectModel;
using System.Linq;

using ConsoleFx.Validators;

namespace ConsoleFx.Parsers
{
    public sealed class OptionParameterValidators
    {
        private readonly int _parameterIndex;
        private readonly ValidatorCollection _validators = new ValidatorCollection();

        public OptionParameterValidators(int parameterIndex)
        {
            _parameterIndex = parameterIndex;
        }

        public int ParameterIndex
        {
            get { return _parameterIndex; }
        }

        public ValidatorCollection Validators
        {
            get { return _validators; }
        }
    }

    //Collection of all parameter validators of an option. The collection is grouped by parameter index
    public sealed class OptionParameterValidatorsCollection : KeyedCollection<int, OptionParameterValidators>
    {
        public void Add(BaseValidator validator)
        {
            Add(ParameterIndex.First, validator);
        }

        public void Add(int parameterIndex, BaseValidator validator)
        {
            OptionParameterValidators validatorsByIndex = this[parameterIndex];
            if (validatorsByIndex == null)
            {
                validatorsByIndex = new OptionParameterValidators(parameterIndex);
                Add(validatorsByIndex);
            }
            validatorsByIndex.Validators.Add(validator);
        }

        public void AddForAllParameters(BaseValidator validator)
        {
            Add(ParameterIndex.All, validator);
        }

        protected override int GetKeyForItem(OptionParameterValidators item)
        {
            return item.ParameterIndex;
        }

        public new OptionParameterValidators this[int parameterIndex]
        {
            get
            {
                if (Dictionary != null)
                {
                    OptionParameterValidators validators;
                    return Dictionary.TryGetValue(parameterIndex, out validators) ? validators : null;
                }
                return this.FirstOrDefault(vals => vals.ParameterIndex == parameterIndex);
            }
        }
    }
}